package com.baway.demo_recyclerview

import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide

/**
 * @Author : ZhouZiYao
 * @Time : On 2023/11/29 14:05
 * @Description :
 */
class VideoAdapter: RecyclerView.Adapter<VideoAdapter.VideoViewHolder>() {

    companion object{
        const val TAG = "VideoAdapter"
    }

    private val list = mutableListOf<Data>()

    fun setList(list: MutableList<Data>){
        this.list.clear()
        this.list.addAll(list)
        notifyDataSetChanged()//全局刷新
    }

    fun addBean(position:Int, bean:Data){
        this.list.add(position, bean)
        notifyItemInserted(position)//局部刷新，只刷新当前item
    }
    fun removeBean(position:Int){
        this.list.removeAt(position)
        notifyItemRemoved(position)//局部刷新，只刷新当前item
    }
    fun updateBean(position: Int,bean: Data){
        this.list[position] = bean
        notifyItemChanged(position)//局部刷新，只刷新当前item
    }

    fun updateBean(position: Int,bean: Data,payload:String){
        this.list[position] = bean
        notifyItemChanged(position,payload)//局部增量刷新，只刷新当前item
    }

    //viewHolder
    class VideoViewHolder(itemView: View):RecyclerView.ViewHolder(itemView){
        val iv:ImageView = itemView.findViewById(R.id.iv)
        val tv:TextView = itemView.findViewById(R.id.tv)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VideoViewHolder {
        Log.d(TAG, "onCreateViewHolder:创建ViewHolder ")
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_video, parent, false)
        return VideoViewHolder(view)
    }
    //局部增量刷新
    override fun onBindViewHolder(
        holder: VideoViewHolder,
        position: Int,
        payloads: MutableList<Any>
    ) {
        payloads.forEach {
            if(it == "text"){
                holder.tv.text = list[position].description
            }else if(it == "image"){
                Glide.with(holder.itemView.context).load(list[position].videomainimag).into(holder.iv)
            }
        }
        super.onBindViewHolder(holder, position, payloads)
    }

    override fun onBindViewHolder(holder: VideoViewHolder, position: Int) {
        Log.d(TAG, "onBindViewHolder:绑定ViewHolder $position")
        Glide.with(holder.itemView.context).load(list[position].videomainimag).into(holder.iv)
        holder.tv.text = list[position].description
    }

    override fun getItemCount(): Int {
        return list.size
    }
}